package com.hctforgreen.greenservice;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.db.DBFeedbackInfoManager;
import com.hctforgreen.greenservice.encoding.RGBLuminanceSource;
import com.hctforgreen.greenservice.model.FeedBackListEntity.FeedBackEntity;
import com.hctforgreen.greenservice.model.PhotoEntity;
import com.hctforgreen.greenservice.model.ResultEntity;
import com.hctforgreen.greenservice.model.SerieListEntity.SerieEntity;
import com.hctforgreen.greenservice.model.VideoEntity;
import com.hctforgreen.greenservice.ui.adapter.SinglePicListAdapter;
import com.hctforgreen.greenservice.ui.adapter.SingleVideoListAdapter;
import com.hctforgreen.greenservice.ui.adapter.SpinnerStringsAdapter;
import com.hctforgreen.greenservice.ui.widget.DefaultSeriesListPopupView;
import com.hctforgreen.greenservice.ui.widget.GridViewIsChildOfScrollView;
import com.hctforgreen.greenservice.utils.DecodeBitmapUtil;
import com.hctforgreen.greenservice.utils.FileCacheUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.ImageCropUtil;
import com.hctforgreen.greenservice.utils.KeyboardUtil;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;
import com.hctforgreen.greenservice.utils.Utils;
import com.umeng.analytics.MobclickAgent;

/**
 * 提交图文反馈V3
 * 
 * @author Tallen Zhai
 * 
 */
public class SubmitFeedBackActivityV3 extends ParentActivity {
	private final static int FILE_SELECT_CODE = 0x113;
	private final int ZXING_DATA= 3024;
	public final int FLAG_MODIFY_FINISH = 3025;
	private final int RESULT_LOAD_IMAGE = 3023;
	private Bitmap bitmap;// 图库二维码图片
	private Button scan_btn, pic_btn;
	private EditText code_edit;
	private List<PhotoEntity> picList = new ArrayList();
	private SinglePicListAdapter mAdapter;

	private List<VideoEntity> videoList = new ArrayList();
	private SingleVideoListAdapter mVideoAdapter;
	
	/**
	 * 相册
	 */
	public final int PHOTO_PICKED_WITH_DATA = 1;
	public final int VIDEO_PICKED_WITH_DATA = 2;
	public final int FROM_HISTORY = 3;
	private SubmitFeedBackActivityV3 mSelf;

	public int mPosition = -1;

	public FeedBackEntity backEntity;//

	private File uploadFile;// 新增上传文件
	/**
	 * 机组系列
	 */
	private DefaultSeriesListPopupView mSeriesListPopupView;
	private SerieEntity mCurrentFirstEntity;

	private String feedbackType = "";
	private String applianceType = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_submit_feed_back_v2);
		mSelf = this;
		initSkinLayout();
		initClickEdgehideKeyboard();
		initTitleButtonBar();
		initWindow();
		initByFeedback();
		initSubmitBtn();
		initBarcode();//添加条码填写控件
		
	}

	/**
	 * 点击边缘隐藏输入法
	 */
	private void initClickEdgehideKeyboard() {
		LinearLayout rootLyt = (LinearLayout) findViewById(R.id.lyt_root);
		rootLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
			}
		});
	}
	
	/**
	 * 添加条码填写控件
	 * wuhs
	 * 20150909
	 */
	private void initBarcode() {
		
		scan_btn = (Button) findViewById(R.id.scan_btn);
		scan_btn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				Intent intent = new Intent(mSelf, CaptureActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivityForResult(intent, ZXING_DATA);
			}
		});
		pic_btn = (Button) findViewById(R.id.pic_btn);
		pic_btn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				ImageCropUtil util = new ImageCropUtil();
				util.doCropImage(mSelf, FLAG_MODIFY_FINISH);
			}
		});
		
		
	}
	
	
	private void initSubmitBtn() {
		code_edit = (EditText) findViewById(R.id.code_edit);
		final EditText topic_edit = (EditText) findViewById(R.id.title_edit);
		final EditText content_edit = (EditText) findViewById(R.id.content_edit);
		final Button submitBtn = (Button) findViewById(R.id.sub_btn);
		submitBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String barCodeString = code_edit.getText().toString().trim();
				String personId = LoginResultStoreUtil
						.get(SubmitFeedBackActivityV3.this).personId;
				String topic = topic_edit.getText().toString().trim();
				String content = content_edit.getText().toString().trim();
				
				if(!barCodeValidate(barCodeString)){
					
					return;
				}
				
				if (mCurrentFirstEntity == null) {
					Toast.makeText(SubmitFeedBackActivityV3.this,
							R.string.submit_feed_serie_input_not_null_hint,
							Toast.LENGTH_SHORT).show();
					return;
				}

				if (topic.equals("")) {
					Toast.makeText(SubmitFeedBackActivityV3.this,
							R.string.submit_feed_topic_input_not_null_hint,
							Toast.LENGTH_SHORT).show();
					return;
				}

				if (content.equals("")) {
					Toast.makeText(SubmitFeedBackActivityV3.this,
							R.string.submit_feed_content_input_not_null_hint,
							Toast.LENGTH_SHORT).show();
					return;
				}

				List<String> pathList = new ArrayList<String>();
				for (PhotoEntity entity : picList) {
					if (!entity.path.equals("")) {
						pathList.add(entity.path);
					}
				}

				List<String> videoPathes = new ArrayList<String>();
				for (VideoEntity entity : videoList) {
					if (!entity.path.equals("")) {
						videoPathes.add(entity.path);
					}
				}
				sub_text(submitBtn, personId, mCurrentFirstEntity.id, topic,
						content, pathList, videoPathes,barCodeString);

			}
		});
	}

	private void initWindow() {
		View convertView = findViewById(R.id.lyt_parent);
		// initApplianceSpinner();
		// initFeedbackTypeSpinner();
		initSeriesBtn(convertView);
		initSelectFileLayout(convertView);
		initPicGv(convertView);
		
		
	}

	/**
	 * 初始化电器类别
	 */
	private void initApplianceSpinner() {
		Spinner spinner = (Spinner) findViewById(R.id.appliance_spinner);
		spinner.setPrompt(getString(R.string.tag_select_hint));
		final String[] items = getResources().getStringArray(
				R.array.appliance_types);
		applianceType = items[0];
		SpinnerStringsAdapter adapter = new SpinnerStringsAdapter(this, items);
		spinner.setAdapter(adapter);

		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				applianceType = items[arg2];
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

	}

	/**
	 * 初始化反馈类别
	 */
	private void initFeedbackTypeSpinner() {
		Spinner spinner = (Spinner) findViewById(R.id.feedback_spinner);
		spinner.setPrompt(getString(R.string.tag_select_hint));
		final String[] items = getResources().getStringArray(
				R.array.feedback_types);
		feedbackType = items[0];
		SpinnerStringsAdapter adapter = new SpinnerStringsAdapter(this, items);
		spinner.setAdapter(adapter);

		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				feedbackType = items[arg2];
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

	}

	/**
	 * 初始化选择文件
	 * 
	 * @param convertView
	 */
	private void initSelectFileLayout(View convertView) {
		findViewById(R.id.lyt_select_file).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
						intent.setType("*/*");
						intent.addCategory(Intent.CATEGORY_OPENABLE);

						try {
							startActivityForResult(Intent.createChooser(intent,
									"Select a File to Upload"),
									FILE_SELECT_CODE);
						} catch (android.content.ActivityNotFoundException ex) {
							Toast.makeText(SubmitFeedBackActivityV3.this,
									"Please install a File Manager.",
									Toast.LENGTH_SHORT).show();
						}
					}
				});

	}

	public void updateSeriesBtn(SerieEntity currentFirstEntity) {
		mCurrentFirstEntity = currentFirstEntity;

		Button seriesBtn = (Button) findViewById(R.id.btn_series);
		seriesBtn.setText(currentFirstEntity.name);
	}

	private void initSeriesBtn(View convertView) {

		Button seriesBtn = (Button) findViewById(R.id.btn_series);
		if (backEntity != null && !"".equals(backEntity.seriesName)) {
		}
		seriesBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showListPopupView(v);
			}

			private void initListPopupView() {
				mSeriesListPopupView = new DefaultSeriesListPopupView(
						SubmitFeedBackActivityV3.this, mCurrentFirstEntity,
						mSelf);
			}

			private void showListPopupView(View v) {
				initListPopupView();
				if (mSeriesListPopupView.isShowing()) {
					mSeriesListPopupView.dismiss();
				} else {
					mSeriesListPopupView.showAsDropDown(v);
				}
			}
		});
	}

	private void initPicGv(View convertView) {
		if (backEntity != null) {
			if (backEntity.picNames.size() > 0) {
				picList.clear();
				for (String path : backEntity.picNames) {
					PhotoEntity entity = new PhotoEntity();
					entity.path = path;
					picList.add(entity);
				}
			}
			if (!"".equals(backEntity.videoPath)) {
				updateVideoList(backEntity.videoPath);
			}
		}

		GridViewIsChildOfScrollView picGv = (GridViewIsChildOfScrollView) findViewById(R.id.gv_pic);
		mAdapter = new SinglePicListAdapter(picGv,
				SubmitFeedBackActivityV3.this, convertView, picList, mSelf);

		GridViewIsChildOfScrollView videoGv = (GridViewIsChildOfScrollView) findViewById(R.id.gv_video);
		mVideoAdapter = new SingleVideoListAdapter(videoGv,
				SubmitFeedBackActivityV3.this, convertView, videoList, mSelf);
	}

	private void initTitleButtonBar() {
		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(getString(R.string.submit_feed_back_title_hint));

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showExistDialog();
				// finish();
			}
		});
		// final Button btnRight = (Button) findViewById(R.id.btn_right);
		// btnRight.setBackgroundResource(R.drawable.btn_feedback_history_selector);
		// btnRight.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// Intent intent = new Intent(SubmitFeedBackActivityV3.this,
		// FeedbackHistoryActivity.class);
		// startActivityForResult(intent, FROM_HISTORY);
		// }
		// });
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode != RESULT_OK){
			return; 
		}
		switch (requestCode) {
		case RESULT_LOAD_IMAGE:
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();
			readerFromSDCardPath(picturePath);
			break;
		case FLAG_MODIFY_FINISH://根据图片获取条码
			if(resultCode == RESULT_OK&&data != null){
				ImageCropUtil cropUtil = new ImageCropUtil();
				readerFromSDCardPath(cropUtil.getTmpFilePath());
			}
			break;	
		case ZXING_DATA://扫描条码后进入这里
			String result = data.getStringExtra("result");
			if (result == null) {
				return;
			}
			code_edit.setText(result);
			break;
		case PHOTO_PICKED_WITH_DATA: // 相册 图片压缩
			if (resultCode == RESULT_OK) {
				String[] all_path = data.getStringArrayExtra("all_path");
				int newPostion = mPosition;
				for (String selectedImagePath : all_path) {
//					updatePhotoList(zipPhoto(selectedImagePath));
					PhotoEntity entity = new PhotoEntity();
					entity.path = zipPhoto(selectedImagePath);
					entity.position = newPostion;
					if (newPostion < picList.size()) {
						picList.set(newPostion, entity);
						if (picList.size() < 6) {//当图片数少于6时
							boolean bCanAdd = true;//判断是否有新增图片按钮（path为空），没有则为在末端新增图片，故需要在其后增加新增按钮
							for (PhotoEntity photoEntity : picList) {
								if (photoEntity.path.equals("")) {
									bCanAdd = false;
								}
							}
							if (bCanAdd) {
								picList.add(new PhotoEntity());
							}
						}

					} else {
						picList.add(entity);
					}
					newPostion++;
//					PhotoEntity entity = new PhotoEntity();
//					entity.path = zipPhoto(selectedImagePath);
//					entity.position = newPostion;
//					picList.add(entity);
//					newPostion++;
				}
				mAdapter.notifyDataSetChanged();
				
				
				
//				Uri uri = data.getData();
//				String selectedImagePath = getPath(uri);
//
//				if (selectedImagePath == null
//						|| "".equals(selectedImagePath.trim())) {
//					Toast.makeText(mSelf,
//							getString(R.string.feed_back_get_image_fail),
//							Toast.LENGTH_LONG).show();
//					return;
//				}
//				//
//				updatePhotoList(zipPhoto(selectedImagePath));
//				mAdapter.notifyDataSetChanged();
			}
			break;
		case VIDEO_PICKED_WITH_DATA:// 视频
			if (resultCode == RESULT_OK) {
				Uri uri = data.getData();
				String selectedVideoPath = getViedoPath(uri);

				if (selectedVideoPath == null
						|| "".equals(selectedVideoPath.trim())) {
					Toast.makeText(mSelf,
							getString(R.string.feed_back_get_video_fail),
							Toast.LENGTH_LONG).show();
					return;
				}
				Log.w("videoPath", "path:" + selectedVideoPath);
				File file = new File(selectedVideoPath);
				if (!file.exists() || file.length() > 50 * 1024 * 1024) {
					Toast.makeText(mSelf,
							getString(R.string.feed_back_video_length_fail),
							Toast.LENGTH_LONG).show();
					return;
				}

				updateVideoList(selectedVideoPath);
			}
			break;
		// case
		case FROM_HISTORY:// 历史记录
			if (resultCode == RESULT_OK) {
				backEntity = (FeedBackEntity) data
						.getSerializableExtra("feedbackEntity");
				if (backEntity != null) {
					DbController dbController = new DbController(this);
					List<SerieEntity> entities = dbController
							.getSerieEntityLst();
					for (SerieEntity serieEntity : entities) {
						if (serieEntity.name.equals(backEntity.seriesName)) {
							updateSeriesBtn(serieEntity);
							break;
						}
					}
					View convertView = findViewById(R.id.lyt_parent);
					initPicGv(convertView);
					final EditText topic_edit = (EditText) findViewById(R.id.title_edit);
					final EditText content_edit = (EditText) findViewById(R.id.content_edit);
					topic_edit.setText(backEntity.title);
					content_edit.setText(backEntity.content);
				}
			}

			break;
		case FILE_SELECT_CODE:
			if (resultCode == RESULT_OK) {
				// Get the Uri of the selected file
				Uri uri = data.getData();
				String path = FileCacheUtil.getPath(this, uri);
				final TextView tvSelFile = (TextView) findViewById(R.id.tv_select_file);
				if (!TextUtils.isEmpty(path)) {
					tvSelFile.setText(path);
					uploadFile = new File(path);
				} else {
					uploadFile = null;
					tvSelFile.setText(R.string.submit_feed_back_select_file);
					Toast.makeText(
							this,
							getString(R.string.submit_feed_back_select_file_fail),
							Toast.LENGTH_LONG).show();
				}
			}
			break;
		}
	}

	/**
	 * 历史记录跳转
	 */
	private void initByFeedback() {

		backEntity = (FeedBackEntity) getIntent().getSerializableExtra(
				"feedbackEntity");
		if (backEntity != null) {
			DbController dbController = new DbController(this);
			List<SerieEntity> entities = dbController.getSerieEntityLst();
			for (SerieEntity serieEntity : entities) {
				if (serieEntity.name.equals(backEntity.seriesName)) {
					updateSeriesBtn(serieEntity);
					break;
				}
			}
			View convertView = findViewById(R.id.lyt_parent);
			initPicGv(convertView);
			final EditText topic_edit = (EditText) findViewById(R.id.title_edit);
			final EditText content_edit = (EditText) findViewById(R.id.content_edit);
			topic_edit.setText(backEntity.title);
			content_edit.setText(backEntity.content);
			if (!TextUtils.isEmpty(backEntity.uploadFilePath)
					&& new File(backEntity.uploadFilePath).exists()) {
				final TextView tvSelFile = (TextView) findViewById(R.id.tv_select_file);
				tvSelFile.setText(backEntity.uploadFilePath);
			}
		}

	}

	/**
	 * 压缩图片
	 */
	private String zipPhoto(final String photoFile) {
		if (photoFile == null || photoFile.trim().length() == 0) {
			return "";
		}
		File file = new File(photoFile);
		if (!file.exists()) {
			return "";
		}
		File resFile = new File(HctConstants.DEFAULT_ROOT_PATH
				+ HctConstants.DEFAULT_IMG_STORE_PATH + file.getName());
		try {
			if (resFile.getParentFile() == null
					|| !resFile.getParentFile().exists()) {
				resFile.getParentFile().mkdirs();
			}
			if (!resFile.exists()) {
				resFile.createNewFile();
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		BitmapFactory.Options options = new BitmapFactory.Options();
		if (file.length() > 10 * 1024 * 1024) {
			options.inSampleSize = 30;
		} else if (file.length() > 6 * 1024 * 1024) {
			options.inSampleSize = 20;
		} else if (file.length() > 2 * 1024 * 1024) {
			options.inSampleSize = 10;
		} else if (file.length() > 1024 * 1024) {
			options.inSampleSize = 5;
		} else if (file.length() > 1024 * 512) {
			options.inSampleSize = 2;
		} else {
			options.inSampleSize = 1;
		}
		Bitmap bmp = BitmapFactory.decodeFile(photoFile, options);
		try {
			bmp.compress(CompressFormat.JPEG, 75, new FileOutputStream(resFile));
			// FileOutputStream fos = new FileOutputStream(resFile);
			// fos.write(baos.toByteArray());
			// fos.flush();
			// fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resFile.getAbsolutePath();

	}
	
	
	private void updatePhotoList(String selectedImagePath) {
		PhotoEntity entity = new PhotoEntity();
		entity.path = selectedImagePath;
		entity.position = mPosition;

		if (mPosition < picList.size()) {
			picList.set(mPosition, entity);
			if (/* mPosition != 0 && */picList.size() < 6) {
				boolean bCanAdd = true;
				for (PhotoEntity photoEntity : picList) {
					if (photoEntity.path.equals("")) {
						bCanAdd = false;
					}
				}
				if (bCanAdd) {
					picList.add(new PhotoEntity());
				}

			}

		} else {
			picList.add(entity);
		}
	}

	private void updateVideoList(String selectedVideoPath) {
		VideoEntity entity = new VideoEntity();
		entity.path = selectedVideoPath;
		videoList.clear();
		videoList.add(entity);
		mVideoAdapter.notifyDataSetChanged();
	}

	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	public String getViedoPath(Uri uri) {
		String[] projection = { MediaStore.Video.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

	}

	/**
	 * 提交文本反馈
	 * 
	 * @param personId
	 * @param seriesId
	 * @param topic
	 * @param content
	 */
	private void sub_text(final Button sub_btn, final String personId,
			final String seriesId, final String topic, final String content,
			final List<String> filepaths, final List<String> videoPathes, final String barCode) {
		final ProgressBar loadPb = (ProgressBar) findViewById(R.id.pb_loading);
		sub_btn.setClickable(false);
		loadPb.setVisibility(View.VISIBLE);

		MobclickAgent.onEvent(this, "Normal_feadback");
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				sub_btn.setClickable(true);
				loadPb.setVisibility(View.GONE);

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					int points = 2;
					if ((picList != null && picList.size() > 0)
							|| (videoList != null && videoList.size() > 0)) {
						++points;
					}

					Utils.submitPoints(SubmitFeedBackActivityV3.this, points,
							"", false);
					hctResult = (HctResult) msg.obj;
					ResultEntity entity = (ResultEntity) hctResult.data;
					if (entity.statusCode.equals("0")) {
						Toast.makeText(SubmitFeedBackActivityV3.this,
								R.string.add_feed_sucess_hint,
								Toast.LENGTH_SHORT).show();
						setResult(RESULT_OK, getIntent());
						finish();
					} else if (!entity.statusCode.equals("0")) {

						Toast.makeText(SubmitFeedBackActivityV3.this,
								entity.msg, Toast.LENGTH_SHORT).show();
					}
					break;

				case HctConstants.STATUS_FAILD:
					Toast.makeText(SubmitFeedBackActivityV3.this,
							getString(R.string.net_error_hint),
							Toast.LENGTH_SHORT).show();
					break;
				}
			}
		};
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(
							SubmitFeedBackActivityV3.this);

					HctResult result = controller.submitFeedBack(
							personId,
							seriesId,
							topic,
							content,
							filepaths,
							videoPathes,
							uploadFile == null ? "" : uploadFile
									.getAbsolutePath(), applianceType,
							feedbackType, barCode);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();
	}

	@Override
	public void onBackPressed() {
		showExistDialog();
	}

	/**
	 * 显示是否保存草稿对话框
	 */
	private void showExistDialog() {
		final EditText topic_edit = (EditText) findViewById(R.id.title_edit);
		final EditText content_edit = (EditText) findViewById(R.id.content_edit);
		final String topic = topic_edit.getText().toString().trim();
		final String content = content_edit.getText().toString().trim();
//		final String barcode = code_edit.getText().toString().trim();
		

		if (mCurrentFirstEntity == null || "".equals(topic)
				|| "".equals(content)) {
			finish();
			return;
		}
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle(getString(R.string.feedback_exist_wran_title))
				.setMessage(getString(R.string.feedback_exist_wran_info))
				.setPositiveButton(getString(R.string.feedback_exist_leave),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								finish();
							}
						})
				.setNegativeButton(getString(R.string.feedback_exist_cancel),
						null)
				.setNeutralButton(getString(R.string.feedback_exist_save),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								boolean update = true;
								if (backEntity == null) {
									update = false;
									backEntity = new FeedBackEntity();
								}
								SimpleDateFormat dateFormat = new SimpleDateFormat(
										"yyyy-MM-dd HH:mm:ss");

//								backEntity.barcode = barcode;
								backEntity.answerContent = content;
								backEntity.answerName = topic;
								backEntity.seriesName = mCurrentFirstEntity.name;
								backEntity.submitDate = dateFormat
										.format(new Date());
								if (picList != null && picList.size() > 1) {
									StringBuffer sb = new StringBuffer();
									for (int i = 0; i < picList.size(); i++) {
										if (i == 0) {
											sb.append(picList.get(i).path);
										} else {
											if (!"".equals(picList.get(i).path)) {
												sb.append(
														FeedBackEntity.PIC_FILE_SEPRATOR)
														.append(picList.get(i).path);
											}
										}
									}
									backEntity.picPathes = sb.toString();
								}
								if (videoList != null && videoList.size() > 0) {
									if (!"".equals(videoList.get(0).path)) {
										backEntity.videoPath = videoList.get(0).path;
									}
								}
								if (uploadFile != null && uploadFile.exists()) {
									backEntity.uploadFilePath = uploadFile
											.getAbsolutePath();
								}
								DBFeedbackInfoManager dbFeedbackInfoManager = new DBFeedbackInfoManager(
										getApplicationContext());
								if (update) {
									dbFeedbackInfoManager.updateMsg(backEntity);
									setResult(RESULT_OK);
								} else {
									dbFeedbackInfoManager.add(backEntity);
								}
								finish();
							}
						}).create().show();

	}

	private void readerFromSDCardPath(String picturePath) {
		try {
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
				bitmap = null;
			}
			DecodeBitmapUtil decodeBitmapUtil = new DecodeBitmapUtil();
			bitmap = decodeBitmapUtil.getHorizontalBitmap(picturePath);

			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			RGBLuminanceSource source = new RGBLuminanceSource(bitmap);
			BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
			MultiFormatReader reader2 = new MultiFormatReader();
			Result result;
			try {
				result = reader2.decode(bitmap1, hints);
				code_edit.setText(result.getText());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Utils.showToastCenter(mSelf,
						getString(R.string.not_found_the_barcode_hint));
			}
		} catch (Exception e) {
		}
	}
	/**
	 * 条码校验
	 */
	private boolean barCodeValidate(String barcode){

		//判断是否有中文
		if(!barcode.isEmpty()){//不为空再校验
			
			if (Utils.chineseValid(barcode)) {
				Utils.showToastCenter(mSelf,
						getString(R.string.barcode_length_is_zh));
				return false;
			}
			
			if (!(barcode.length() == 13
					|| barcode.length() == 15 || barcode
					.length() == 30)) {
				Utils.showToastCenter(
						mSelf,
						getString(R.string.barcode_length_is_wrong));
				return false;
			}
		}
		
		return true;
	}
	
}
